package xiao_jin.fantastic_journey.server;

import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.Identifier;
import xiao_jin.fantastic_journey.api.capability.CapabilityPayload;
import xiao_jin.fantastic_journey.util.ModUtil;

public final class FantasticJourneyServer implements DedicatedServerModInitializer {
    @Override
    public void onInitializeServer() {
        registerNetwork();
    }

    private void registerNetwork() {
        PayloadTypeRegistry.playS2C().register(CapabilityPayload.PAYLOAD_ID, CapabilityPayload.CODEC);
        PayloadTypeRegistry.playC2S().register(CapabilityPayload.PAYLOAD_ID, CapabilityPayload.CODEC);

        ServerPlayNetworking.registerGlobalReceiver(CapabilityPayload.PAYLOAD_ID, ((pl, context) ->
                serverPacket(pl.getCapName(), context.player(), pl)));
    }

    private void serverPacket(Identifier id, ServerPlayerEntity player, CapabilityPayload payload) {
        ModUtil.registerCapability(id, payload, player.PC$getOrCreateNBTTagCompound(), player);
    }
}
